
import React, { Component } from 'react'
import { Form, Input, Radio, InputNumber, Button, message, Spin, Tabs } from 'antd'
import getData from '@/Utils/fecth'
import Title from '@/components/Title'
import Peer from './Peer'
import TabsList from './Tabs'
import _ from 'lodash'
import { address } from '@/Utils/apiConfig'

const { addCloudPeer } = address.leagueManagement
class CreatePeer extends Component {
  constructor(props) {
    super(props)
    this.state = {
      mode: 'out',
      org_expiration: 1,
      peerList: [],
      detail: {},
      // 初始值
      initialValues: {
        num: '',
        performance: 'ecs.c5.large',
        node_expiration: 1,

      },
      // 右边当前选中值
      currentValues: {
        num: '',
        performance: '',
        node_expiration: 1,
        total_price: '',
      },
      loading: true,
    }
  }
    formRef = React.createRef();
    componentDidMount() {
      this.getPeerData()
    }
    // 表单真实的数据提交
    onFinish = async(values) => {
      this.setState({
        loading: true,
      })
      let messageError = {
        // 409: "此域名已使用！",
        default: '创建节点失败',
      }
      const objValues = {
        orgId: this.props.match.params.id,
        run_mode: 'cloud',
        ...values,
      }
      let res = await getData().post(addCloudPeer, objValues)
      this.setState({
        loading: false,
      })
      if (res && res.status === 200) {
        message.success('创建节点成功!')
        this.props.history.goBack()
      } else {
        message.error(_.get(messageError, _.get(res, 'status', 'default')))
      }
    }

    onChange = (values) => {
      let currentValues = {
        ...this.state.currentValues,
        ...values,
      }
      this.setState({
        currentValues,
      })
    }
    submit = () => {
      this.formRef.current.submit()
    }
    createPeer = async(values) => {
      const options = {
        orgId: this.props.match.params.id,
        run_mode: 'bare',
        nodes: this.state.peerList.map(element => {
          return {
            name: element.name,
            ip: element.host,
            user: element.username,
            _pwd: element._pwd,
          }
        }),
      }
      let res = await getData().post(addCloudPeer, options)
      this.setState({
        loading: false,
      })
      if (res && res.status === 200) {
        message.success('创建节点成功!')
        this.props.history.goBack()
      } else {
        message.error('创建节点失败!')
      }
    }
    getPeerData = async() => {
      let res = await getData().get(address.organizationManagement.organizationDetail.format({ id: this.props.match.params.id }))
      if (res && res.status === 200 && res.data && res.data.length) {
        let performance = {
          'high-level': '高级版',
          'ecs.c5.large': '标准版',
        }
        this.setState({
          loading: false,
          initialValues: {
            ...this.state.currentValues,
            performance: res.data[0].node_performance,
          },
          currentValues: {
            ...this.state.currentValues,
            performance: _.get(performance, res.data[0].node_performance),
          },
        })
      } else {
        this.setState({
          loading: false,
        })
      }
    }
    render() {
      const {
        initialValues,
        currentValues,
        loading,
        detail,
      } = this.state
      const org_expiration = {
        1: '一个月',
        6: '半年',
        12: '一年',
      }
      return (
        <div className="fabric-create-org fabric-create-peer common">
          <Spin spinning={loading} >
            <TabsList>
              <div className="tabs-wrapper">
                <Title title="填写配置" />
                <div>
                  <Form className="create-form" onFinish={this.createPeer} hideRequiredMark={true} ref={(ref) => this.form = ref}>
                    <Form.Item
                      name="peer"
                      label="新增节点："
                    >
                      <Peer form={this.form} flag="peerList" getForm={() => { return this.form }} onChange={(key, list) => {
                        this.setState({
                          [key]: list,
                        })
                      }} />

                    </Form.Item>
                    <Form.Item>
                      <Button htmlType="submit" className="submit com-normal-btn com-btn-primary" type="primary">提&nbsp;交</Button>
                    </Form.Item>
                  </Form>
                </div>
              </div>
              <div style={{ display: 'flex', alignItems: 'flex-start' }}>
                <div className="tabs-wrapper">
                  <Title title="填写配置" />
                  <Form className="create-form bare-form "
                    ref={this.formRef}
                    onValuesChange={(changedValues, allValues) => this.onChange(changedValues)}
                    initialValues={initialValues} onFinish={this.onFinish} >
                    <Form.Item
                      label={<div className="select">增加数量</div>}
                      className="form-item form-item-required"
                    >
                      <Form.Item noStyle name="num" rules={[
                        { required: true, message: '请选择增加数量！' },
                      ]}>
                        <InputNumber min={0} autoComplete="off" parser={value => value.replace(/\$\s?|(,*)(\.*)/g, '')} />
                      </Form.Item>
                    </Form.Item>
                    <Form.Item
                      name="performance"
                      label="节点规格"
                      className="form-item"
                      // rules={[
                      //     { required: true, message: '请选择节点规格！' },
                      // ]}
                    >
                      <Radio.Group>
                        <Radio.Button value="ecs.c5.large" disabled={this.state.initialValues.performance !== 'ecs.c5.large'}>基础版</Radio.Button>
                        {/* <Radio.Button value="high-level" disabled={this.state.initialValues.performance !== 'high-level'}>高级版</Radio.Button> */}
                      </Radio.Group>
                    </Form.Item>
                    <div className="diver"></div>
                    <Form.Item
                      name="node_expiration"
                      label="购买时长"
                      className="form-item"
                    >
                      <Radio.Group>
                        <Radio.Button value={1}>一个月</Radio.Button>
                        <Radio.Button value={6}>半年</Radio.Button>
                        <Radio.Button value={12}>一年</Radio.Button>
                      </Radio.Group>
                    </Form.Item>
                  </Form>
                </div>

                <div className="org-current-info current-info">
                  <Title title="当前配置" />
                  <div className="info">

                    <div className="item-info">
                      <span className="item-text">增加数量</span>
                      <span className="item-value">{Number(currentValues.node_num) || '-'}</span>
                    </div>
                    <div className="item-info">
                      <span className="item-text">节点规格</span>
                      <span className="item-value">{currentValues.performance || '-'}</span>
                    </div>
                    <div className="diver"></div>
                    <div className="item-info">
                      <span className="item-text">购买时长</span>
                      <span className="item-value">{_.get(org_expiration, currentValues.org_expiration)}</span>
                    </div>
                    <div className="diver"></div>
                    <div className="item-info">
                      <span className="item-text">配置费用</span>
                      <span className="item-value"><span className="symbol">¥</span>11988.00</span>
                    </div>
                  </div>
                  <div className="btn">
                    <Button className="buy-btn com-btn-primary" onClick={() => this.submit()} type="submit">立即购买</Button>
                  </div>

                </div>
              </div>

            </TabsList>
          </Spin>

        </div>
      )
    }
}
export default CreatePeer

